package security.Authentication.Encrypted;

import java.net.InetAddress;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import security.Authentication.Base.AuthenticationRequest;

/**
 * Request with encrypted user name and password
 * @author Andreas Carmvall
 */
public class EncryptedRequest extends AuthenticationRequest {

	/**
	 * The encrypted user name
	 */
	private byte[] encryptedUserName;
	/**
	 * The encrypted password
	 */
	private byte[] encryptedPassword;

	/**
	 * Class constructor
	 * @param address the address from where the request was sent
	 * @param userName the user name
	 * @param password the password
	 */
	public EncryptedRequest(InetAddress address, String userName, String password) {
		super(address);
		
		try {
			this.encryptedUserName = encryptText(userName.getBytes());
			this.encryptedPassword = encryptText(password.getBytes());
		} catch (GeneralSecurityException e) {
			this.encryptedUserName = null;
			this.encryptedPassword = null;
		}
	}
	
	/**
	 * Get the request user name
	 * @return the encrypted user name
	 */
	public byte[] getEncryptedUserName() {
		return encryptedUserName;
	}
	
	/**
	 * Get the request password
	 * @return the encrypted password
	 */
	public byte[] getEncryptedPassword() {
		return encryptedPassword;
	}

	/**
	 * Encrypt a text with AES
	 * @param text the bytes to be encrypted
	 * @return the encrypted bytes
	 * @throws GeneralSecurityException if the encryption failed
	 */
	private byte[] encryptText(byte[] text) throws GeneralSecurityException {
		final String passphrase = "This is the passphrase."; // Use a fixed passphrase
		Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
		MessageDigest digest = MessageDigest.getInstance("SHA");
		
		digest.update(passphrase.getBytes());
		SecretKeySpec key = new SecretKeySpec(digest.digest(), 0, 16, "AES");
		aes.init(Cipher.ENCRYPT_MODE, key);
		
		byte[] ciphertext = aes.doFinal(text);
		
		return ciphertext;
	}
}
